//
//  YHTabBar.swift
//  新浪
//
//  Created by lcc on 16/5/11.
//  Copyright © 2016年 lcc. All rights reserved.
//

import UIKit

protocol yhTabBarDelegate: NSObjectProtocol {

    //点击撰写按钮回调方法
    func didSelectedComposeButton()
}

class YHTabBar: UITabBar {
    //设置闭包
    var composeButtonClosure: (()->())?
    
    //设置代理
    weak var yhDelegate = yhTabBarDelegate?()
    
    private lazy var composeButton: UIButton = {
        
        let button = UIButton()
        //添加点击事件
        button.addTarget(self, action: "composeButtonClick", forControlEvents: .TouchUpInside)
        
        //设置背景图片
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button" ), forState:.Normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted" ), forState:.Highlighted)
        //设置图片
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState:.Normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: .Highlighted)
        //自适应
        button.sizeToFit()
        
        return button
    }()
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        //调用
        setUpUI()
    }
    
    
    //加载xib或者storyBoard时候调用
    required init?(coder aDecoder: NSCoder) {
//        fatalError("init(coder:) has not been implemented")
        //支持xib的写法
        super.init(coder: aDecoder)
        
        setUpUI()
    }
    
    private func setUpUI() {
        
        addSubview(composeButton)
    }
    
    //设置加号按钮位置
    override func layoutSubviews() {
        super.layoutSubviews()
        
        //设置位置
        composeButton.center.x = frame.size.width * 0.5
        composeButton.center.y = frame.size.height * 0.5
        
        //计算子视图按钮大小
        let itemWidth = frame.size.width / 5
        var index = 0
        //遍历子视图
        for childView in subviews {
            if childView.isKindOfClass(NSClassFromString("UITabBarButton")!) {
                //设置子视图宽度
                childView.frame.size.width = itemWidth
                //设置x
                childView.frame.origin.x = itemWidth * CGFloat(index)
                index++
                if index == 2 {
                    index++
                }
            }
        }
    }
    
    //点击按钮实现
    //@objc告诉系统我们使用动态运行机制，去调用这个函数
   @objc private func composeButtonClick() {
        print("点击了加号按钮-")
        
        composeButtonClosure?()
    
    //代理方法实现点击按钮事件
//        yhDelegate?.didSelectedComposeButton()
    }
}
